package com.example.kingweather.utils;

import com.example.kingweather.bean.AirBean;
import com.example.kingweather.bean.WeatherBean;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.schedulers.Schedulers;

public class HttpUtils {

    private static HttpUtils httpUtils;
    private String Url = "https://free-api.heweather.net/s6/";
    private BaseApis baseApis;


    //单例
    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            synchronized (HttpUtils.class) {
                httpUtils = new HttpUtils();
            }
        }

        return httpUtils;
    }


    private HttpUtils() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(Url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();


        baseApis = retrofit.create(BaseApis.class);
    }


    public Observable<WeatherBean> getNowWeather(String location) {
        return baseApis.getNowWeather(location)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io());
    }

    public Observable<AirBean> getNowAir(String location) {
        return baseApis.getNowAir(location)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io());
    }

}
